import { MciInput, MciButton, MciNotification, MciSubCard, MciTable, MciTableColumn, MciTooltip } from '@/components/base';
import { ElForm, ElFormItem, ElDrawer } from 'element-plus';
import { postDecisionExecute, IPostDecisionExecuteRes } from '@/api';
import { useDictStore } from '@/store/dict';
import { millisecond } from '@/utils/math';
import { IFormItem } from './types';
import './index.scss';

export const OnLine = defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const dictStore = useDictStore();
    const formRef = ref<InstanceType<typeof ElForm>>();
    const flowVars = ref<Record<string, any>>({});
    const formFields = ref<IFormItem[]>([]);
    const result = ref({} as IPostDecisionExecuteRes);
    const loading = ref(false);

    const initData = async () => {
      const data = props.params.value?.data || []
      if (data && data.length !== 0) {
        formFields.value = data.filter(item => item.varName !== 'flowId' && item.varName !== 'decisionId').map((item) => ({
          label: item.varLabel!,
          name: item.varName!,
          defaultValue: item.initValue || ''
        }));
        flowVars.value = Object.fromEntries(data.map((item) => [item.varName, item.initValue]));
      }
    };

    const onConfirm = () => {
      formRef.value?.validate(async (valid) => {
        if (valid) {
          // 触发自定义事件将数据传回父组件
          // emit('formSubmit', { ...flowVars.value });
          loading.value = true;
          const params = {
            ...flowVars.value,
            decisionId: props.params.value.decisionId,
          }
          try {
            const res = await postDecisionExecute(params);
            result.value = res;
          } finally {
            loading.value = false;
          }
        }
      });
    };

    const handleClose = () => {
      emit('update:modelValue', false);
      result.value = {};
    };

    // 复制路径
    const copyResParams = (data: any) => {
      if (navigator.clipboard && data) {
        const placeholders = Object.keys(data);
        navigator.clipboard.writeText(data).then(() => {
          MciNotification.success('复制成功');
        });
      }
    };


    // 复制为JSON
    const copyParams = (data: any) => {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(JSON.stringify(data || {}, null, 2)).then(() => {
          MciNotification.success('复制成功');
        });
      }
    };
    // 格式化返回结果参数
    const getResponseList = (resultItem: any) => {
      if (!resultItem) return [];
      let result = resultItem.flatMap((item, outerIndex) => {
        // 删除 _rule_name 属性
        const newItem = { ...item };
        delete newItem._rule_name;
    
        // 转换为新的格式
        return Object.entries(newItem).map(([key, value], index) => ({
          // ['col_' + (outerIndex * Object.keys(item).length + index)]: value,
          ['col_' + 0]: value,
          label: key
        }));
      });
      return result;
    };
    
    // 格式化详情的参数
    const getDetailList = (obj: any) => {
      if (Object.keys(obj).length === 0) return [];
      const data = [];
      data.push(obj)
      return data;
    };

    // 审批状态
    const decisionStatus = (data: number) => {
      switch (data) {
        case -1:
          return '拒绝';
        case 0:
          return '待审批';
        case 1:
          return '通过';
        default:
          break;
      }
    };

    watch(
      () => props.modelValue,
      (val) => {
        if (!val) {
          formRef.value?.resetFields();
        } else {
          initData();
        }
      }
    );

    return () => {
      
      return (
        <ElDrawer
          destroyOnClose
          size={1000}
          direction="rtl"
          onClose={handleClose}
          appendToBody
          v-model={props.modelValue}>
          {{
            header() {
              return <div class="text-value-16_bold ">在线执行</div>;
            },
            default() {
              return (
                <div class="online-detail py-12 flex flex-col gap-20">
                  <MciSubCard title={'请求入参：'}>
                    <ElForm ref={formRef} model={flowVars.value} labelPosition="top" style="padding: 12px;">
                      <ElFormItem class="flex-path" label="请求路径：" prop="path">
                        <span>{props.params.value?.path}</span>
                        <MciButton
                          type="primary"
                          link={true}
                          class="ml-12"
                          onClick={() => copyResParams(props.params.value?.path)}
                        >
                          复制
                        </MciButton>
                      </ElFormItem>
                      {formFields.value.map((field) => (
                        <ElFormItem
                          label={field.label}
                          prop={field.name}
                          rules={[
                            {
                              required: true,
                              message: `请输入${field.label}`,
                              trigger: ['change', 'blur']
                            }
                          ]}>
                          <MciInput v-model={flowVars.value[field.name]} placeholder={`请输入${field.label}`} />
                        </ElFormItem>
                      ))}
                      <ElFormItem
                        label='隐藏'
                        style="display: none;"
                        prop='hidden'>
                        <MciInput />
                      </ElFormItem>
                      <ElFormItem class="btnClass">
                        <MciButton type="primary" class="mt-12" onClick={() => onConfirm()} loading={loading.value}>
                          执行
                        </MciButton>
                      </ElFormItem>
                    </ElForm>
                  </MciSubCard>
                  <MciSubCard title={'请求结果：'}>
                    <div class="px-16">
                      {!!result.value?.execResult?.length && (
                        <>
                          <div class="flex justify-between mt-20">
                            <span class="!text-gray-600 text-value-16_bold">请求返回的结果</span>
                            <MciButton onClick={() => copyParams(result.value?.execResult)} type="info">
                              复制为JSON
                            </MciButton>
                          </div>
                          <div v-loading={loading.value}>
                            <MciTable maxHeight={400} data={getResponseList(result.value?.execResult)}>
                              <MciTableColumn label="字段描述" prop="label" />
                              <MciTableColumn label="" prop="col_0" />
                            </MciTable>
                          </div>
                        </>
                      )}
                      {!!Object.keys(result.value).length !== 0 && (
                        <>
                          <div class="flex justify-between mt-20">
                            <span class="!text-gray-600 text-value-16_bold">相关信息</span>
                            <MciButton onClick={() => copyParams(result.value)} type="info">
                              复制为JSON
                            </MciButton>
                          </div>
                          <div class="flex items-center justify-end gap-12"></div>
                          <div v-loading={loading.value}>
                            <MciTable maxHeight={300} data={getDetailList(result.value)}>
                              <MciTableColumn label="决策流编号" prop="flowId">
                                {(scope: any) => (
                                  <>
                                    <MciTooltip content={`${scope.row.flowId}`}>
                                      <p class="textAlgin">{ scope.row.flowId }</p>
                                    </MciTooltip>
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="决策流名称" prop="flowName">
                                {(scope: any) => (
                                  <>
                                    <MciTooltip content={`${scope.row.flowName}`}>
                                      <p class="textAlgin">{ scope.row.flowName }</p>
                                    </MciTooltip>
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="结果编号" prop="execId">
                                {(scope: any) => (
                                  <>
                                    <MciTooltip content={`${scope.row.execId}`}>
                                      <p class="textAlgin">{ scope.row.execId }</p>
                                    </MciTooltip>
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="完成状态" prop="execStatus">
                                {(scope: any) => (
                                  <>
                                    <p>
                                      { dictStore.dictExecStatusMap[scope.row.execStatus] }
                                    </p>
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="决策结果" prop="decisionRet">
                                {(scope: any) => (
                                  <>
                                    {
                                      <p style={{ color: `${scope.row.decisionRet === -1 ? 'var(---5-text, #E34D59)' : scope.row.decisionRet === 1 ? 'var(---5-text, #00AC97)' : 'var(--color-text-5)'}` }}>
                                        { decisionStatus(scope.row.decisionRet) }
                                      </p>
                                    }
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="错误信息" prop="errorMsg">
                                {(scope: any) => (
                                  <>
                                    {
                                      scope.row.errorMsg ? <MciTooltip content={`${scope.row.errorMsg}`}>
                                        <p class="textAlgin">
                                          { scope.row.errorMsg }
                                        </p>
                                      </MciTooltip> : <p>--</p>
                                    }
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="耗用时间" prop="spendTime">
                                {(scope: any) => (
                                  <>
                                    <p>
                                      { scope.row.spendTime ? millisecond(scope.row.spendTime) : '--' }
                                    </p>
                                  </>
                                )}
                              </MciTableColumn>
                              <MciTableColumn label="调用模式" prop="调用模式">
                                {(scope: any) => (
                                  <>
                                    <p>
                                      { scope.row.testMode ? '测试模式' : '正常调用' }
                                    </p>
                                  </>
                                )}
                              </MciTableColumn>
                            </MciTable>
                          </div>
                        </>
                      )}
                    </div>
                  </MciSubCard>
                </div>
              );
            }
          }}
        </ElDrawer>
      );
    };
  }
});
